package com.qmyx.supply.admin.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Value;

import java.util.Arrays;
import java.util.List;

/**
 * 自定义 Banker Realm
 */
public class VirtualAccountRealm extends AuthorizingRealm {

    @Value("${virtual.accounts:}")
    private String accounts;

    private final static String SALT="test**";

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //加这一步的目的是在Post请求的时候会先进认证，然后在到请求
        if (authenticationToken.getPrincipal() == null) {
            return null;
        }
        //获取用户手机号
        String tel = authenticationToken.getPrincipal().toString();
        List<String> tels = Arrays.asList(accounts.split(","));
        if (!tels.contains(tel)) {
            //这里返回后会报出对应异常
            return null;
        } else {
            String resultPwd = new Md5Hash("qmyx123456", SALT,2).toString();
            //这里验证authenticationToken和simpleAuthenticationInfo的信息
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(tel, resultPwd, getName());
            // 加盐的方式可随机字符
            simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(SALT));
            return simpleAuthenticationInfo;
        }
    }
}
